package com.handu.luna.core.domain.promotion;

import com.handu.luna.core.domain.user.User;
import com.handu.luna.core.domain.user.UserRank;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.Entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by wangzailiang on 2014/6/19 0019.
 */
@Entity
public class Coupon extends Bonus {



    /**
     * 通过优惠券类型ID查询所有优惠券(分页)
     * @param couponPromotionId
     * @param pageable
     * @return
     */
    public Page<Coupon> findAllByCouponPromotionId(Long couponPromotionId,Pageable pageable) {
        Page<Coupon> page = context.getCouponRepository().findAllByBonusPromotionId(couponPromotionId, pageable);
        List<Coupon> list = page.getContent();
        for(Coupon coupon : list) {
            coupon.init();
        }
        return page;
    }

    /**
     * 通过优惠券类型ID查询所有优惠券
     * @param couponPromotionId
     * @return
     */
    public List<Coupon> findAllByCouponPromotionId(Long couponPromotionId) {
        List<Coupon> list = context.getCouponRepository().findAllByBonusPromotionId(couponPromotionId);
        for(Coupon coupon : list) {
            coupon.init();
        }
        return list;
    }

    /**
     * 优惠券Excel导出
     * @param couponPromotionId
     * @return
     */
    public HSSFWorkbook getExcelModel(Long couponPromotionId) {

        List<Coupon> couponList = new Coupon().findAllByCouponPromotionId(couponPromotionId);

        HSSFWorkbook wb = new HSSFWorkbook();
        int sheetCount = couponList.size()/60000 + 1;
        int beginIndex = 0;
        int endIndex = sheetCount > 1 ? 60000 : couponList.size();

        for (int sheetNum = 1; sheetNum <= sheetCount; sheetNum++) {

            HSSFSheet sheet = wb.createSheet("优惠券"+(sheetCount > 1 ? sheetNum :""));
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("优惠券序列号");
            headerRow.createCell(1).setCellValue("优惠券金额");
            headerRow.createCell(2).setCellValue("类型名称");
            headerRow.createCell(3).setCellValue("使用结束日期");

            for(int i=beginIndex,j=0; i<endIndex; i++,j++) {
                Coupon coupon = couponList.get(i);

                Row row = sheet.createRow(j+1);
                row.createCell(0).setCellValue(coupon.getCode());
                row.createCell(1).setCellValue(coupon.getBonusPromotion().getBonusPrice().toString());
                row.createCell(2).setCellValue(coupon.getBonusPromotion().getName());
                String strDate = "";
                if(coupon.getBonusPromotion().getUseEndDate() != null) {
                    strDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(coupon.getBonusPromotion().getUseEndDate());
                }
                row.createCell(3).setCellValue(strDate);
            }

            beginIndex = 60000 * sheetNum;
            endIndex = sheetCount > (sheetNum+1) ? 60000*(sheetNum + 1) : couponList.size();
        }

        return wb;

    }

    public void delete(Long id,Long couponPromotionId) {
        Coupon coupon = context.getCouponRepository().findOne(id);
        CouponPromotion couponPromotion = context.getCouponPromotionRepository().findOne(couponPromotionId);
        couponPromotion.updateGrantNum(couponPromotionId, -1L);
        if(StringUtils.isNotBlank(coupon.getOrderId())) {
            couponPromotion.updateUsedNum(couponPromotionId,-1L);
        }
        context.getCouponRepository().delete(id);
    }

    /**
     * 生成序列号
     */
    public void generateCode() {
        StringBuilder code = new StringBuilder(String.valueOf(bonusPromotionId));
        code.append(System.nanoTime());
        setCode(code.toString());
    }

    /**
     * 初始化优惠券类型数据
     */
    public void init() {
        this.setBonusPromotion(context.getCouponPromotionRepository().findOne(bonusPromotionId));
        if(userId != null) {
            this.setUser(context.getUserRepository().findOne(userId));
        }
    }

    public Coupon save(Coupon coupon) {
        coupon.generateCode();
        context.getCouponRepository().save(coupon);
        return coupon;
    }


    public String getSucessFlashMessage(String message){
        String messagePrefix = (null==this.getId() ?"添加" : "修改");
        return messagePrefix + message + "成功";
    }

    public Coupon() {

    }

    public Coupon(String code, Long userId, String orderId, Date usedDate, Long bonusPromotionId) {
        super(code,userId,orderId,usedDate);
        this.bonusPromotionId = bonusPromotionId;
    }


    /**
     * 根据类型ID 和发放数量 发放
     * @param couponPromotionId
     * @param grantNum
     */
    public void save(Long couponPromotionId, Long grantNum) {

        for(int i=0; i<grantNum; i++) {
            Coupon coupon = new Coupon();
            coupon.setBonusPromotionId(couponPromotionId);
            this.save(coupon);
        }

        new CouponPromotion().updateGrantNum(couponPromotionId, grantNum);
    }

    public Long saveByUserRankId(Long userRankId,Long couponPromotionId) {

        UserRank userRank = context.getUserRankRepository().findOne(userRankId);
        List<User> userList = context.getUserRepository().findbyLevelPoint((int)userRank.getMinRank(),(int)userRank.getMaxRank());

        long grantNum = 0L;

        for(User user : userList) {
            Coupon coupon = new Coupon();
            coupon.generateCode();
            coupon.setBonusPromotionId(couponPromotionId);
            coupon.setUserId(user.getId());
            this.save(coupon);
            grantNum++;
        }

        new CouponPromotion().updateGrantNum(couponPromotionId, grantNum);

        return grantNum;
    }

    public Long saveByUsersId(List<Long> userIds, Long couponPromotionId) {

        long grantNum = 0L;

        for(Long id: userIds) {
            Coupon coupon = new Coupon();
            coupon.generateCode();
            coupon.setBonusPromotionId(couponPromotionId);
            coupon.setUserId(id);
            this.save(coupon);
            grantNum++;
        }

        new CouponPromotion().updateGrantNum(couponPromotionId, grantNum);

        return grantNum;
    }
}
